/**
 * By Alpha
 * Author: alixez <alixe.z@foxmail.com>
 * Date: 2017/11/3
 */

/* global window */

import React, { Component } from 'react';
import NProgress from 'nprogress';
import PropTypes from 'prop-types';
import pathToRegexp from 'path-to-regexp';
import { connect } from 'dva';
import { Affix, LocaleProvider } from 'antd';
import { Layouts, Loader } from 'components';
import { classNames, config } from 'utils';
import { Helmet } from 'react-helmet';
import { withRouter } from 'dva/router';
import zhCN from 'antd/lib/locale-provider/zh_CN';
import moment from 'moment';
import 'moment/locale/zh-cn';
import '../themes/index.less';
import './App.less';

moment.locale('zh-cn');

const { Header, Sider, Layout, styles } = Layouts;
let { openPages } = config;
let loadLocationHref = null;

// 开放页面列表
openPages = openPages.map(_ => (typeof _ === 'string' ? _ : _.path));

class App extends Component {
  static propTypes = {
    children: PropTypes.element.isRequired,
    location: PropTypes.object,
    dispatch: PropTypes.func,
    app: PropTypes.object,
    user: PropTypes.object,
    loading: PropTypes.object,
  };

  _getPathname = () => {
    let { location: { pathname } } = this.props;

    pathname = pathname.startsWith('/') ? pathname : `/${pathname}`;
    return pathname;
  }

  // 登出处理器
  _logoutHandler = () => {
    console.log("== 登出");
    const { dispatch } = this.props;
    dispatch({
      type: 'user/logout',
    });
  }

  render () {
    const { children, app, user, loading, location } = this.props;
    const { menus } = app;

    const { organizations, organization, school, userInfo } = user;
    // let { pathname } = location;
    // 为 pathname 加上前缀
    let pathname = this._getPathname();

    const { logo } = config;

    const href = window.location.href;

    if (loadLocationHref !== href) {
      // 3s 后若还没有加载完，则直接关掉加载状态
      setTimeout(() => {
        if (loading.global) {
          NProgress.done();
          loadLocationHref = href;
        }
      }, 3000);
      // NProgress.done();
      NProgress.start();
      if (!loading.global) {
        NProgress.done();
        loadLocationHref = href;
      }
    }

    const headerProps = {
      user: userInfo,
      organizations,
      organization,
      school,
      location,
      logoutHandler: this._logoutHandler,
    };

    const siderProps = {
      menu: menus,
      location,
    };

    if (openPages && openPages.includes(pathname)) {
      return (<LocaleProvider locale={zhCN} ><div>
        <Loader fullScreen spinning={loading.effects['app/load']} />
        {children}
      </div></LocaleProvider>);
    }
    return (
      <LocaleProvider locale={zhCN}>
        <div>
          <Loader fullScreen spinning={loading.effects['app/load']} />
          <Helmet>
            <title>UNITE | 游离体 </title>
            <meta name="viewport" content="width=device-width, initial-scale=1.0" />
            <link rel="icon" href={logo} type="image/x-icon" />
          </Helmet>

          <Layout className={classNames(styles.layout)}>
            <Affix className={styles.headerAffix}>
              <Header {...headerProps} />
            </Affix>

            <Layout>
              {menus.length === 0 ? null : <Sider {...siderProps} />}
              <Layout className={styles.main}>
                <Layout.Content className={styles.container}>
                  <div className={styles.content}>
                    {children}
                  </div>
                </Layout.Content>
              </Layout>
            </Layout>
          </Layout>
        </div>
      </LocaleProvider>
    );
  }
}

export default withRouter(connect(({ app, user, loading }) => ({ app, user, loading }))(App));
